var dataSource;
var listSrcs = Array();
var srcType;
var srcId;
var act = false;
var firstLoad = true;
var moes        = 0;
var areas       = 0;
var lineas      = 0;
var estaciones  = 0;
var moesList  = [];
var areasList = [];
var linesList = [];
var worksList = [];

if (appBosch.src_id !== 0) {
    srcType = appBosch.src_type;
    srcId = appBosch.src_id;
    listSrcs[srcType] = srcId;
    act = true;
}

$('#moes').val("");
$('#areas').val("");
$('#lineas').val("");
$('#estaciones').val("");

$(document).ready(function() {
    $('#grid').on('click', '.seeImage', verImagen );

    dataSource = new kendo.data.DataSource({
        transport: {
            create: {
                url: appBosch.crud.create,
                dataType: "json"
            },
            read: {
                url: appBosch.crud.read + '/' + kendo.stringify(listSrcs),
                dataType: "json"
            },
            update: {
                url: appBosch.crud.update,
                dataType: "json"
            },
            destroy: {
                url: appBosch.crud.destroy,
                dataType: "json"
            },
            parameterMap: function(options, operation) {
                var params = {};
                switch (operation)
                {
                    case 'create':
                        params = {models: kendo.stringify(options.models)};
                    case 'read':
                        break;
                    case 'update':
                        params = {models: kendo.stringify(options.models)};
                        break;
                    case 'destroy':
                        params = {id: options.models[0].value};
                }
                return params;
            }
        },
        batch: true,
        schema: {
            model: {
                id: "value",
                fields: {
                    text: {
                        editable: true,
                        nullable: false,
                        validation: {
                            required: true,
                            min: 1
                        }
                    },
                    img: {
                        type: "string",
                        editable: true,
                        nullable: true
                    },
                    vid: {
                        type: "string",
                        editable: true,
                        nullable: true
                    },
                    selec: {
                        type: "number",
                        editable: false
                    },
                    mandatory: {
                        type: "boolean",
                        editable: true
                    },
                    required: {
                        type: "boolean",
                        editable: true
                    },
                    admissible_answers:{
                        type: "number",
                        defaultValue : 1,
                        editable: true
                    },
                    src_id: {
                        type: "string",
                        editable: true,
                        defaultValue: appBosch.src_id
                    },
                    src_type: {
                        type: "string",
                        editable: false,
                        defaultValue: appBosch.src_type
                    }
                }
            }
        }
    });
        
    initHIerarchy();

    $("#grid").kendoGrid({
        toolbar: [
            {
                name: "create",
                text: "Agregar pregunta"
            },
            {
                name: "excel",
                text: "Exportar a Excel"
            },
            {
                name: "pdf",
                text: "Exportar a PDF"
            }
        ],
        excel: {
            allPages: true,
            fileName: "Preguntas.xlsx",
            filterable: true
        },
        pdf: {
            allPages: true,
            fileName: "Preguntas.pdf"
        },
        autoBind: act,
        scrollable: true,
        filterable: true,
        selectable: true,
        navigatable: true,
        resizable: true,
        columnMenu: true,
        dataSource: dataSource,
        columns: [
            {field: "text", title: "Pregunta" },
            {
                field: "img",
                title: "Imagen",
                editor: imgEditor,
                template: "#if(img !== null && img !== undefined){# <button class='seeImage k-button k-button-icontext'>Ver imagen</button>#}#",
                width: 150
            },
            {
                field: "vid",
                title: "Video",
                editor: vidEditor,
                template: "#if(vid !== null && vid !== undefined){# <i class='fa fa-check'></i> #}#",
                width: 150
            },
            {
                field: "selec",
                title: "Seleccionable",
                template: kendo.template($("#templateSelec").html()),
                width: 90
            },
            {
                field: "mandatory",
                title: "Correcta",
                template: kendo.template($("#templateMand").html()),
                width: 90
            },
            {
                field: "required",
                title: "Obligatoria",
                template: kendo.template($("#templateRequired").html()),
                width: 90
            },
            {
                field: "admissible_answers",
                title: "Mínimo de respuestas",
                width: 90
            },
            {
                field: "src_type",
                title: "Tipo de pregunta",
                template: '# if (src_type == 1) {# MOE #} else if (src_type == 2) {# Área #} else if (src_type == 3) {# Línea #} else if (src_type == 4) {# Estación #} #',
                width: 120
            },
            {
                field: "src_id",
                hidden: true,
                editor: setDefaults
            },
            {command: [
                    {name: "respuestas", text: "Respuestas", click: showAnswers},
                    {
                        name: "edit",
                        text: {
                            edit: "",
                            update: "",
                            cancel: ""
                        }
                    },
                    {
                        name: "destroy",
                        text: ""
                    }], title: "&nbsp;"}],
        editable: {
            confirmation: "¿Estás seguro que deseas eliminar esta pregunta?",
            mode: "inline"
        },
        cancel: function () {
            $.post(appBosch.cancel);
        }
    });
    
    $(".k-grid-add").on('click', function(e){//$("#grid").on('click','.k-grid-add', function(e){
        e.stopPropagation();
        if( $("#moes").val() ){
            $("#grid").data("kendoGrid").addRow();
        }else{
            $("#dlgAlertCreate").kendoWindow({
                title: "Crear pregunta",
                modal:true,
                visible: false,
                width: 280,
                height: 60,
                animation: {
                    open: {
                        effects: "fade:in"
                    }
                }
            });
            $("#dlgAlertCreate").data("kendoWindow").center().open();
        }
        
    });
});

function imgEditor(container, options) {
    var input = $("<input type='file' id='image' />");
    input.attr("name", options.field);
    input.appendTo(container);
    input.kendoUpload({
        async: {
            saveUrl: appBosch.upload + '/1'
        },
        localization: {
            select: "Seleccionar...",
            headerStatusUploaded: "",
            headerStatusUploading: "",
            statusUploaded: "",
            statusUploading: ""
        },
        complete: function () {
            options.model.set('img', 'Ok');
        },
        multiple: false
    });
}

function vidEditor(container, options) {
    var input = $("<input type='file' id='video' />");
    input.attr("name", options.field);
    input.appendTo(container);
    input.kendoUpload({
        async: {
            saveUrl: appBosch.upload + '/2'
        },
        localization: {
            select: "Seleccionar...",
            headerStatusUploaded: "",
            headerStatusUploading: "",
            statusUploaded: "",
            statusUploading: ""
        },
        complete: function () {
            options.model.set('vid', 'Ok');
        },
        multiple: false
    });
}

function verImagen (e) {
    var dataItem = $(e.currentTarget).closest("tr");
    dataItem = dataSource.getByUid(dataItem.data('uid'));
    $("<div><img src='" + dataItem.img + "?" + Math.floor((Math.random() * 10) + 1).toString() + "' width='1000px' /></div>").kendoWindow({
        //width: "",
        title: "Imagen",
        actions: [
            "Close"
        ]
    }).data("kendoWindow").open().center();
}

function showAnswers(e)
{
    e.preventDefault();
    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
    var id = dataItem.id;
    var url = appBosch.crud.answer + '/' + id;
    var wnd = $("<div id='wndAnswers'></div>");

    $.get(url, {}, function(res) {
        wnd.html(res);
        wnd = wnd.kendoWindow({
            width: "60%",
            title: "Respuestas",
            actions: [
                "Close"
            ]
        }).data("kendoWindow").open().center();
        wnd.bind("deactivate", function () {
            wnd.destroy();
            dataSource.read();
        });
        activateAnswers(id);
    });
}

function setDefaults(container, options) {
    options.model.src_id = srcId;
    options.model.src_type = srcType;
}

function activateAnswers(question_id) {
    $('#gridA').on('click', '.seeImage', verImagenA );

    dataSourceA = new kendo.data.DataSource({
        transport: {
            create: {
                url: appBosch.Answers.create,
                dataType: "json"
            },
            read: {
                url: appBosch.Answers.read + '/' + question_id,
                dataType: "json"
            },
            update: {
                url: appBosch.Answers.update,
                dataType: "json"
            },
            destroy: {
                url: appBosch.Answers.destroy,
                dataType: "json"
            },
            parameterMap: function(options, operation) {
                var params = {};
                switch (operation)
                {
                    case 'create':
                        params = {models: kendo.stringify(options.models)};
                    case 'read':
                        break;
                    case 'update':
                        params = {models: kendo.stringify(options.models)};
                        break;
                    case 'destroy':
                        params = {id: options.models[0].value};
                }
                return params;
            }
        },
        batch: true,
        schema: {
            model: {
                id: "value",
                fields: {
                    text: {
                        editable: true,
                        nullable: false,
                        validation: {
                            required: true,
                            min: 1
                        }
                    },
                    img: {
                        type: "string",
                        editable: true,
                        nullable: true
                    },
                    ok: {
                        type: "boolean",
                        editable: true,
                        nullable: false
                    },
                    src_id: {
                        defaultValue: question_id
                    }
                }
            }
        }
    });

    $("#gridA").kendoGrid({
        scrollable: true,
        filterable: true,
        selectable: true,
        navigatable: true,
        resizable: true,
        columnMenu: true,
        dataSource: dataSourceA,
        excel: {
            fileName: "Respuestas.xlsx",
            filterable: true
        },
        pdf: {
            allPages: true,
            fileName: "Respùestas.pdf"
        },
        toolbar: [
            {
                name: "create", 
                text: "Agregar respuesta"
            },
            {
                name: "pdf", 
                text: "Exportar a PDF" 
            }, 
            { 
                name: "excel", 
                text: "Exportar a Excel"
            }
        ],
        columns: [
            {field: "text", title: "Respuesta" },
            {
                field: "img",
                title: "Imagen",
                editor: imgEditorA,
                template: "#if(img !== null && img !== undefined && img !== ''){# <button class='seeImage k-button k-button-icontext'>Ver imagen</button> #}#",
                width: 300
            },
            {
                field: "ok",
                title: "Es correcta",
                template: kendo.template($("#templateOk").html())
            },
            {command: [
                {
                    name: "edit",
                    text: {
                        edit: "",
                        update: "",
                        cancel: ""
                    }
                },
                {
                    name: "destroy",
                    text: ""
                }], title: "&nbsp;"}],
        editable: {
            confirmation: "¿Estas seguro que deseas eliminar esta respuesta?",
            mode: "inline"
        },
        cancel: function () {
            $.post(appBosch.Answers.cancel);
        }
    });

    function verImagenA (e) {
        var dataItem = $(e.currentTarget).closest("tr");
        dataItem = dataSourceA.getByUid(dataItem.data('uid'));

        $("<div><img src='" + dataItem.img + "?" + Math.floor((Math.random() * 10) + 1).toString() + "' width='1000px' /></div>").kendoWindow({
            width: "1000px",
            title: "Imagen",
            actions: [
                "Close"
            ]
        }).data("kendoWindow").open().center();
    }
}

function imgEditorA(container, options) {
    var input = $("<input type='file' id='image' />");
    input.attr("name", options.field);
    input.appendTo(container);
    input.kendoUpload({
        async: {
            saveUrl: appBosch.Answers.upload
        },
        localization: {
            select: "Seleccionar...",
            headerStatusUploaded: "",
            headerStatusUploading: "",
            statusUploaded: "",
            statusUploading: ""
        },
        complete: function () {
            options.model.set('img', 'Ok');
        },
        multiple: false
    });
}

function initHIerarchy(){
    
    moes = $("#moes").kendoDropDownList({
        filter: "contains",
        placeholder: "Elige el MOE...",
        dataTextField: "text",
        dataValueField: "value",
        dataSource: moesList,
        dataBound: function(){
            this.select(0);
        },
        change: function(e) {
            srcType     = 1;
            srcId       = e.sender.dataItem().value;
            listSrcs[0] = e.sender.dataItem().value;
            dataSource.transport.options.read.url = appBosch.crud.read + '/' + kendo.stringify(listSrcs);
            dataSource.read();
            loadAreas();
        }
    }).data("kendoDropDownList");
    
    areas = $("#areas").kendoDropDownList({
        autoBind: false,
        cascadeFrom: "moes",
        filter: "contains",
        placeholder: "Elige el Área...",
        dataTextField: "text",
        dataValueField: "value",
        dataSource: areasList,
        dataBound: function(){
            if( firstLoad )
                this.select(0);
        },
        change: function(e) {
            if (e.sender.dataItem().value !== '0') {
                srcType = 2;
                srcId = e.sender.dataItem().value;
                listSrcs[1] = e.sender.dataItem().value;
                dataSource.transport.options.read.url = appBosch.crud.read + '/' + kendo.stringify(listSrcs);
                dataSource.read();
            } else {
                srcType = 1;
                srcId = moes.value();
                listSrcs = listSrcs.slice(0, 1);
                dataSource.transport.options.read.url = appBosch.crud.read + '/' + kendo.stringify(listSrcs);
                dataSource.read();
            }
            loadLines();
        }
    }).data("kendoDropDownList");
    
    lineas = $("#lineas").kendoDropDownList({
        autoBind: false,
        cascadeFrom: "areas",
        filter: "contains",
        placeholder: "Elige la Línea...",
        dataTextField: "text",
        dataValueField: "value",
        dataSource: linesList,
        dataBound: function(){
            if( firstLoad )
            {
                this.select(0);
                firstLoad = false;
            }
        },
        change: function(e) {
            if (e.sender.dataItem().value !== '0') {
                srcType = 3;
                srcId = e.sender.dataItem().value;
                listSrcs[2] = e.sender.dataItem().value;
                dataSource.transport.options.read.url = appBosch.crud.read + '/' + kendo.stringify(listSrcs);
                dataSource.read();
            } else {
                srcType = 2;
                srcId = areas.value();
                listSrcs = listSrcs.slice(0, 2);
                dataSource.transport.options.read.url = appBosch.crud.read + '/' + kendo.stringify(listSrcs);
                dataSource.read();
            }
            loadWorkstations();
        }
    }).data("kendoDropDownList");
    
    estaciones = $("#estaciones").kendoDropDownList({
        autoBind: false,
        cascadeFrom: "lineas",
        filter: "contains",
        placeholder: "Elige la Estación...",
        dataTextField: "text",
        dataValueField: "value",
        dataSource: worksList,
        change: function(e) {
            if (e.sender.dataItem().value !== '0') {
                srcType = 4;
                srcId = e.sender.dataItem().value;
                listSrcs[3] = e.sender.dataItem().value;
                dataSource.transport.options.read.url = appBosch.crud.read + '/' + kendo.stringify(listSrcs);
                dataSource.read();
            } else {
                srcType = 3;
                srcId = lineas.value();
                listSrcs = listSrcs.slice(0, 3);
                dataSource.transport.options.read.url = appBosch.crud.read + '/' + kendo.stringify(listSrcs);
                dataSource.read();
            }
        }
    }).data("kendoDropDownList");
    
    $.get( appBosch.urlMoes )
        .done(function( data ) {
            moesList = data;
            moes.setDataSource( new kendo.data.DataSource({'data': moesList}) );
        });
    $.get( appBosch.urlAAreas )
        .done(function( data ) {
            areasList = data;
            areas.setDataSource( new kendo.data.DataSource({'data': areasList}) );
        });
    $.get( appBosch.urlALines )
        .done(function( data ) {
            linesList = data;
            lineas.setDataSource( new kendo.data.DataSource({'data': linesList}) );
        });
    $.get( appBosch.urlAWorks )
        .done(function( data ) {
            worksList = data;
            estaciones.setDataSource( new kendo.data.DataSource({'data': worksList}) );
        });
}

function setComboData(list, kCombo){
    kCombo.setDataSource( new kendo.data.DataSource({'data': list}) );
}

function loadHierarchy(){
    loadAreas();
    loadLines();
    loadWorkstations();
}

function loadAreas(){
    var moe_id = moes.value();
    if( moe_id ){
        var moeAreas = [];
        for( var i = 0; i < areasList.length; i++ ){
            var area = areasList[i];
            if( area.moe_id === undefined || ( area.moe_id && area.moe_id === moe_id ) ){
                moeAreas.push(area);
                
            }
        }
        setComboData(moeAreas,areas);
    }
}

function loadLines(){
    var moe_id = moes.value();
    var area_id = areas.value();
    if( moe_id && area_id ){
        var moeLines = [];
        for( var i = 0; i < linesList.length; i++ ){
            var line = linesList[i];
            if( line.moe_id === undefined || 
                ( line.moe_id && line.area_id && line.moe_id === moe_id && line.area_id === area_id ) ){
                moeLines.push(line);
            }
        }
        setComboData(moeLines,lineas);
    }
}

function loadWorkstations(){
    var moe_id      = moes.value();
    var area_id     = areas.value();
    var lines_id    = lineas.value();
    if( moe_id && area_id && lines_id ){
        var moeWs = [];
        for( var i = 0; i < worksList.length; i++ ){
            var ws = worksList[i];
            if( ws.moe_id === undefined || 
                ( ws.moe_id && ws.area_id && ws.line_id && 
                    ws.moe_id === moe_id && 
                    ws.area_id === area_id && 
                    ws.line_id === lines_id ) ) {
                moeWs.push(ws);
            }
        }
        setComboData(moeWs,estaciones);
    }
}